package com.ktjy.service.impl;

import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Objects;

@Service
public class MailService {
    @Resource
    JavaMailSender javaMailSender;


    public void send(String from, String to, String subject, String content, String fileName, File file, String... cc) throws MessagingException {
        // 创建邮箱服务
        MimeMessage mimeMailMessage = javaMailSender.createMimeMessage();
        // 创建MimeMessageHelper对象，用于构建邮件消息
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMailMessage, true);
        // 设置邮件发送者地址
        messageHelper.setFrom(from);
        // 设置邮件接收者地址
        messageHelper.setTo(to);
        // 设置邮件主题
        messageHelper.setSubject(subject);
        // 设置邮件正文内容
        messageHelper.setText(content);
        // 如果抄送地址不为空且长度大于0，则设置抄送地址
        if (Objects.nonNull(cc) && cc.length > 0) {
            messageHelper.setCc(cc);
        }

        // 判断非空
        if (Objects.nonNull(file) && Objects.nonNull(fileName)) {
            messageHelper.addAttachment(fileName, file);
        }
        // 发送邮件
        javaMailSender.send(mimeMailMessage);
    }
}
